const authModel = require('../models/authModel');
const { sendSuccess, sendError } = require('../utils/response');

module.exports = {
  // 用户注册
  async register(req, res) {
    try {
      const { username, email, password, phone,role } = req.body;
      
      if (!username || !email || !password || !phone) {
        return sendError(res, '请填写完整信息', 400);
      }
      
     
      
      const userId = await authModel.register(username, email, password, phone,role);
      sendSuccess(res, { user_id: userId }, '注册成功', 201);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 用户登录
  async login(req, res) {
    try {
      const { email, password } = req.body;
      
      if (!email || !password) {
        return sendError(res, '邮箱和密码不能为空', 400);
      }
      
      const { user, token } = await authModel.login(email, password);
      sendSuccess(res, {user,token} , '登录成功');
    } catch (err) {
      sendError(res, err.message);
    }
  },  // 用户登录
  async loginUsername(req, res) {
    try {
      const { username, password } = req.body;
      
      if (!username || !password) {
        return sendError(res, '邮箱和密码不能为空', 400);
      }
      
      const { user, token } = await authModel.loginUsername(username, password);
      sendSuccess(res, {user,token} , '登录成功');
    } catch (err) {
      sendError(res, err.message);
    }
  },
  async loginByPhone(req,res){
    try {
      const { phone, password } = req.body;
      
      if (!phone || !password) {
        return sendError(res, '手机号和密码不能为空', 400);
      }
      
      const { user, token } = await authModel.loginByPhone(phone, password);
      sendSuccess(res, {user,token} , '登录成功');
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 获取当前用户信息
  async getCurrentUser(req, res) {
    try {
      const user = await authModel.getCurrentUser(req.user.id);

      sendSuccess(res, user);
    } catch (err) {
      sendError(res, err.message);
    }
  }
};